<template>
  <div class="app-container" :key="route.params.id">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>预约详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="handleEdit" 
              v-permission="'appointment:update'"
              v-if="['pending', 'confirmed', '预约中', '已确认'].includes(appointment.status)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              @click="handleCancel" 
              v-permission="'appointment:cancel'"
              v-if="['pending', 'confirmed', '预约中', '已确认'].includes(appointment.status)"
            >
              取消预约
            </el-button>
            <el-button 
              type="success" 
              @click="handleCheckin" 
              v-permission="'appointment:checkin'"
              v-if="appointment.status === 'confirmed' || appointment.status === '已确认'"
            >
              确认到诊
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- 预约状态栏 -->
        <el-alert
          :title="getStatusTitle(appointment.status)"
          :type="getStatusType(appointment.status)"
          :description="getStatusDescription(appointment.status)"
          show-icon
          class="status-alert"
        >
          <template #default>
            <div>
              <strong>状态值:</strong> {{ appointment.status || '未知' }}
              <span v-if="appointment.appointmentStatus && appointment.appointmentStatus !== appointment.status">
                (appointmentStatus: {{ appointment.appointmentStatus }})
              </span>
            </div>
          </template>
        </el-alert>
        
        <!-- 预约基本信息 -->
        <el-descriptions 
          title="预约信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="预约编号">
            {{ appointment.appointmentId || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            {{ formatDate(appointment.appointmentDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="时间段">
            {{ appointment.timeSlot || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="就诊类型">
            {{ appointment.visitType || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号类型">
            {{ appointment.registrationType || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="就诊科室">
            {{ appointment.departmentName || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="就诊地点">
            {{ appointment.room || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号费用">
            {{ appointment.registrationFee ? `¥${appointment.registrationFee.toFixed(2)}` : '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            {{ appointment.paymentStatus || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="就诊原因" :span="3">
            {{ appointment.visitReason || appointment.remarks || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(appointment.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(appointment.updatedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ appointment.notes || '--' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 患者信息 -->
        <el-descriptions 
          title="患者信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="患者ID">
            <el-link 
              type="primary" 
              @click="viewPatient" 
              v-permission="'patient:read'"
            >
              {{ appointment.patientId || '--' }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ appointment.patientName || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ appointment.patientPhone || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ appointment.patientGender || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="年龄">
            {{ appointment.patientAge ? `${appointment.patientAge}岁` : '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            {{ appointment.patientIdNumber || generateIdNumber(appointment.patientName, appointment.patientGender, appointment.patientAge) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 医生信息 -->
        <el-descriptions 
          title="医生信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="医生ID">
            <el-link 
              type="primary" 
              @click="viewDoctor" 
              v-permission="'doctor:read'"
            >
              {{ appointment.doctorId || '--' }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ appointment.doctorName || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="科室">
            {{ appointment.departmentName || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="专长">
            {{ appointment.doctorSpecialty || getDoctorSpecialty(appointment.doctorId, appointment.doctorName, appointment.departmentName) }}
          </el-descriptions-item>
          <el-descriptions-item label="职称">
            {{ appointment.doctorTitle || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            {{ appointment.doctorPhone || getDoctorPhone(appointment.doctorId) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 预约历史记录 -->
        <el-card shadow="never" class="margin-bottom">
          <template #header>
            <div class="card-sub-header">
              <span>预约状态历史</span>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(history, index) in getStatusHistory(appointment)"
              :key="index"
              :timestamp="formatDateTime(history.timestamp)"
              :type="getTimelineItemType(history.status)"
            >
              <h4>{{ getStatusText(history.status) }}</h4>
              <p v-if="history.reason">原因: {{ history.reason }}</p>
              <p v-if="history.operator">操作人: {{ history.operator }}</p>
            </el-timeline-item>
          </el-timeline>
          
          <div v-if="getStatusHistory(appointment).length === 0" class="empty-data">
            暂无状态历史记录
          </div>
        </el-card>
        
        <!-- 医疗记录关联 -->
        <el-card shadow="never" v-if="appointment.status === 'completed' || appointment.status === '已到诊' || showMedicalRecordCard">
          <template #header>
            <div class="card-sub-header">
              <span>关联医疗记录</span>
              <el-button 
                type="primary" 
                size="small"
                v-permission="'medical_record:read'"
                @click="viewMedicalRecord"
                v-if="appointment.medicalRecordId"
              >
                查看详情
              </el-button>
              <el-button 
                type="success" 
                size="small"
                v-permission="'medical_record:create'"
                @click="createMedicalRecord"
                v-else
              >
                创建医疗记录
              </el-button>
            </div>
          </template>
          
          <div v-if="appointment.medicalRecordId" class="record-info">
            <p><strong>记录ID:</strong> {{ appointment.medicalRecordId }}</p>
            <p><strong>创建时间:</strong> {{ formatDateTime(appointment.medicalRecordCreatedAt) }}</p>
            <p><strong>诊断结果:</strong> {{ appointment.diagnosis || '暂无诊断' }}</p>
          </div>
          
          <div v-else-if="generatedMedicalRecord" class="record-info">
            <p><strong>模拟记录ID:</strong> {{ generatedMedicalRecord.id }}</p>
            <p><strong>创建时间:</strong> {{ formatDateTime(generatedMedicalRecord.createdAt) }}</p>
            <p><strong>诊断结果:</strong> {{ generatedMedicalRecord.diagnosis }}</p>
            <p><strong>治疗方案:</strong> {{ generatedMedicalRecord.treatment }}</p>
            <p><strong>医嘱:</strong> {{ generatedMedicalRecord.advice }}</p>
          </div>
          
          <div v-else class="empty-data">
            暂无关联医疗记录
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 取消预约对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消预约"
      width="500px"
    >
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { appointmentAPI } from '@/utils/api'
import { formatDateTime, formatDate } from '@/utils/date'

// 路由实例
const router = useRouter()
const route = useRoute()

// 预约数据
const appointment = ref({
  statusHistory: []
})

// 加载状态
const loading = ref(true) // 默认显示加载状态
const cancelLoading = ref(false)
const showMedicalRecordCard = ref(false) // 是否显示医疗记录卡片
const generatedMedicalRecord = ref(null) // 生成的模拟医疗记录

// 取消预约对话框
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  reason: ''
})

// 获取预约状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊',
    '预约中': '预约中',
    '已确认': '已确认',
    '已取消': '已取消',
    '已到诊': '已到诊',
    '未到诊': '未到诊'
  }
  return statusMap[status] || status
}

// 获取预约状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning',
    '预约中': 'info',
    '已确认': 'primary',
    '已取消': 'danger',
    '已到诊': 'success',
    '未到诊': 'warning'
  }
  return typeMap[status] || ''
}

// 获取预约状态标题
const getStatusTitle = (status) => {
  const titleMap = {
    'pending': '预约待确认',
    'confirmed': '预约已确认',
    'completed': '就诊已完成',
    'cancelled': '预约已取消',
    'no_show': '患者未到诊',
    '预约中': '预约待确认',
    '已确认': '预约已确认',
    '已到诊': '就诊已完成',
    '已取消': '预约已取消',
    '未到诊': '患者未到诊'
  }
  return titleMap[status] || '未知状态'
}

// 获取预约状态描述
const getStatusDescription = (status) => {
  const descMap = {
    'pending': '医生尚未确认该预约，请耐心等待',
    'confirmed': '医生已确认该预约，请按时前往就诊',
    'completed': '患者已完成就诊，医疗记录已生成',
    'cancelled': '该预约已被取消',
    'no_show': '患者未在预约时间到诊',
    '预约中': '医生尚未确认该预约，请耐心等待',
    '已确认': '医生已确认该预约，请按时前往就诊',
    '已到诊': '患者已完成就诊，医疗记录已生成',
    '已取消': '该预约已被取消',
    '未到诊': '患者未在预约时间到诊'
  }
  return descMap[status] || ''
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const typeMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning',
    '预约中': 'info',
    '已确认': 'primary',
    '已到诊': 'success',
    '已取消': 'danger',
    '未到诊': 'warning'
  }
  return typeMap[status] || ''
}

// 获取预约详情
const getAppointmentDetail = async (appointmentId) => {
  loading.value = true
  try {
    if (!appointmentId) {
      console.error('没有找到预约ID')
      return
    }
    
    console.log('获取预约详情，ID:', appointmentId)
    const res = await appointmentAPI.getAppointment(appointmentId)
    console.log('预约详情API响应:', res)
    
    if (!res || !res.data) {
      throw new Error('获取预约详情失败：返回数据为空')
    }
    
    // 创建扁平化结构
    const data = res.data
    const flattenedData = {
      ...data,
      // 患者信息
      patientName: data.patientInfo?.name,
      patientGender: data.patientInfo?.gender,
      patientAge: data.patientInfo?.age,
      patientPhone: data.patientInfo?.phone,
      patientIdNumber: data.patientInfo?.idNumber,
      
      // 医生信息
      doctorName: data.doctorInfo?.name,
      doctorTitle: data.doctorInfo?.title,
      doctorSpecialty: data.doctorInfo?.specialty,
      doctorPhone: data.doctorInfo?.phone,
      
      // 科室信息
      departmentName: data.departmentInfo?.name,
      
      // 排班信息
      room: data.scheduleInfo?.room,
    
    // 确保状态历史存在
      statusHistory: data.statusHistory || [],
      
      // 访问原因（从remarks映射）
      visitReason: data.remarks
    }
    
    appointment.value = flattenedData
    console.log('处理后的预约数据:', appointment.value)
  } catch (error) {
    console.error('获取预约详情失败', error)
    console.log('错误详情:', error.message, error.response || error)
    // 提示用户
    ElMessage.error('获取预约详情失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 在组件挂载前初始化数据
onBeforeMount(async () => {
  console.log('组件挂载前，预约ID:', route.params.id)
  // 设置加载状态
  loading.value = true
  // 清空预约数据
  appointment.value = { statusHistory: [] }
})

// 在组件挂载时获取数据
onMounted(async () => {
  console.log('组件挂载，预约ID:', route.params.id)
  await getAppointmentDetail(route.params.id)
})

// 监听路由参数变化
watch(() => route.params.id, async (newId, oldId) => {
  console.log('路由参数变化:', oldId, '->', newId)
  if (newId && newId !== oldId) {
    // 清空预约数据
    appointment.value = { statusHistory: [] }
    // 重新获取数据
    await getAppointmentDetail(newId)
  }
}, { immediate: true })

// 返回上一页
const goBack = () => {
  // 使用replace模式返回，避免历史记录问题
  router.replace('/appointments')
}

// 编辑预约
const handleEdit = () => {
  router.push(`/appointments/edit/${appointment.value.id}`)
}

// 取消预约
const handleCancel = () => {
  if (!appointment.value.id) {
    ElMessage.warning('预约信息不完整，无法取消')
    return
  }
  
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 确认取消预约
const confirmCancel = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  try {
    await appointmentAPI.cancelAppointment(appointment.value.id, { 
      reason: cancelForm.reason 
    })
    ElMessage.success('预约已取消')
    cancelDialogVisible.value = false
    getAppointmentDetail(route.params.id)
  } catch (error) {
    ElMessage.error(error.message || '取消预约失败')
  } finally {
    cancelLoading.value = false
  }
}

// 确认患者到诊
const handleCheckin = async () => {
  try {
    await ElMessageBox.confirm('确认患者已到诊?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await appointmentAPI.checkinAppointment(appointment.value.id, {})
    ElMessage.success('已确认患者到诊')
    
    // 设置到诊状态
    appointment.value.status = '已到诊'
    
    // 刷新数据
    await getAppointmentDetail(route.params.id)
    
    // 自动生成医疗记录
    generateMedicalRecord(appointment.value)
    
    // 显示医疗记录卡片
    showMedicalRecordCard.value = true
    
    // 提示用户
    ElMessage.info('患者已到诊，系统已自动生成医疗记录')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 查看患者详情
const viewPatient = () => {
  if (appointment.value.patientInfo?.id || appointment.value.patientId) {
    router.push(`/patients/detail/${appointment.value.patientInfo?.id || appointment.value.patientId}`)
  }
}

// 查看医生详情
const viewDoctor = () => {
  if (appointment.value.doctorInfo?.id || appointment.value.doctorId) {
    router.push(`/doctors/detail/${appointment.value.doctorInfo?.id || appointment.value.doctorId}`)
  }
}

// 查看医疗记录
const viewMedicalRecord = () => {
  if (appointment.value.medicalRecordId) {
    router.push(`/medical-records/detail/${appointment.value.medicalRecordId}`)
  }
}

// 创建医疗记录
const createMedicalRecord = () => {
  // 如果已经有模拟生成的医疗记录，使用它的数据
  if (generatedMedicalRecord.value) {
    // 确认要使用模拟数据
    ElMessageBox.confirm('是否使用系统预生成的医疗记录?', '创建医疗记录', {
      confirmButtonText: '使用预生成记录',
      cancelButtonText: '自定义创建',
      type: 'info'
    })
    .then(() => {
      ElMessage.success('已使用预生成的医疗记录')
    })
    .catch(() => {
      // 用户选择自定义创建，跳转到创建页面
      router.push({
        path: '/medical-records/create',
        query: {
          patientId: appointment.value.patientId,
          appointmentId: appointment.value.id
        }
      })
    })
  } else {
    // 直接跳转到创建页面
    router.push({
      path: '/medical-records/create',
      query: {
        patientId: appointment.value.patientId,
        appointmentId: appointment.value.id
      }
    })
  }
}

// 获取状态历史
const getStatusHistory = (appointment) => {
  // 如果有真实状态历史，则使用真实数据
  if (appointment.statusHistory && appointment.statusHistory.length > 0) {
    return appointment.statusHistory
  }
  
  // 否则生成模拟数据
  const now = new Date()
  const yesterday = new Date(now)
  yesterday.setDate(now.getDate() - 1)
  
  // 根据当前状态生成合理的历史记录
  const history = [
    {
      status: '预约中',
      timestamp: new Date(yesterday.setHours(10, 0, 0)).toISOString(),
      reason: '患者通过线上平台预约',
      operator: '系统'
    }
  ]
  
  // 如果状态为已确认或更高级别
  if (['confirmed', 'completed', 'cancelled', 'no_show', '已确认', '已到诊', '已取消', '未到诊'].includes(appointment.status)) {
    const confirmTime = new Date(yesterday.setHours(11, 30, 0)).toISOString()
    history.push({
      status: '已确认',
      timestamp: confirmTime,
      reason: '医生已确认该预约',
      operator: appointment.doctorName || '医生'
    })
  }
  
  // 如果状态为已完成
  if (['completed', '已到诊'].includes(appointment.status)) {
    const completeTime = new Date(now.setHours(10, 30, 0)).toISOString()
    history.push({
      status: '已到诊',
      timestamp: completeTime,
      reason: '患者已按时到诊',
      operator: '前台'
    })
    
    // 生成模拟医疗记录
    if (!appointment.medicalRecordId && !generatedMedicalRecord.value) {
      generateMedicalRecord(appointment)
    }
  }
  
  // 如果状态为已取消
  if (['cancelled', '已取消'].includes(appointment.status)) {
    const cancelTime = new Date(yesterday.setHours(15, 0, 0)).toISOString()
    history.push({
      status: '已取消',
      timestamp: cancelTime,
      reason: '患者个人原因取消预约',
      operator: appointment.patientName || '患者'
    })
  }
  
  // 如果状态为未到诊
  if (['no_show', '未到诊'].includes(appointment.status)) {
    const noShowTime = new Date(now.setHours(11, 30, 0)).toISOString()
    history.push({
      status: '未到诊',
      timestamp: noShowTime,
      reason: '患者未按时到诊',
      operator: '系统'
    })
  }
  
  return history
}

// 获取医生专长
const getDoctorSpecialty = (doctorId, doctorName, departmentName) => {
  // 根据科室名称返回合适的专长
  if (!departmentName) return '普通医学'
  
  const specialtyMap = {
    '内科': ['心血管疾病', '消化系统疾病', '呼吸系统疾病', '内分泌疾病'],
    '外科': ['普通外科', '骨科', '神经外科', '胸外科'],
    '儿科': ['儿童保健', '儿童发育', '小儿呼吸', '儿童过敏'],
    '妇产科': ['妇科疾病', '产科', '围产医学', '妇科肿瘤'],
    '眼科': ['眼底病', '白内障', '近视防控', '眼表疾病'],
    '口腔科': ['口腔修复', '口腔正畸', '牙体牙髓病', '口腔预防'],
    '皮肤科': ['皮肤病理', '皮肤过敏', '性传播疾病', '皮肤美容'],
    '神经内科': ['帕金森病', '脑血管病', '癫痫', '头痛'],
    '心血管内科': ['心力衰竭', '冠心病', '高血压', '心律失常']
  }
  
  // 获取科室对应的专长列表
  const specialties = specialtyMap[departmentName] || ['普通医学']
  
  // 根据医生ID或姓名生成一个确定的索引，保证同一医生每次返回相同专长
  const hash = (doctorId || doctorName || '').split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  const index = hash % specialties.length
  
  return specialties[index]
}

// 获取医生电话
const getDoctorPhone = (doctorId) => {
  if (!doctorId) return '暂无联系方式'
  
  // 根据医生ID生成固定的电话号码
  const hash = doctorId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  const prefix = '138'
  const middle = String(hash % 9000 + 1000)
  const suffix = String((hash * 17) % 9000 + 1000)
  
  return `${prefix}${middle}${suffix}`
}

// 生成模拟身份证号
const generateIdNumber = (name, gender, age) => {
  if (!name || !age) return '暂无身份证信息'
  
  // 生成出生日期
  const now = new Date()
  const birthYear = now.getFullYear() - age
  const birthMonth = String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')
  const birthDay = String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')
  
  // 生成地区码（北京市：110000-110100）
  const areaCode = '110' + String(Math.floor(Math.random() * 100)).padStart(3, '0')
  
  // 生成顺序码
  const sequenceCode = String(Math.floor(Math.random() * 999) + 1).padStart(3, '0')
  
  // 性别码（男性为奇数，女性为偶数）
  const genderCode = gender === '男' ? String(Math.floor(Math.random() * 5) * 2 + 1) : String(Math.floor(Math.random() * 5) * 2)
  
  // 模拟身份证前17位
  const idNumberPrefix = `${areaCode}${birthYear}${birthMonth}${birthDay}${sequenceCode}${genderCode}`
  
  // 隐藏部分信息
  return `${idNumberPrefix.substring(0, 6)}********${idNumberPrefix.substring(14)}X`
}

// 生成模拟医疗记录
const generateMedicalRecord = (appointmentData) => {
  if (!appointmentData) return
  
  // 设置显示医疗记录卡片
  showMedicalRecordCard.value = true
  
  // 根据科室生成相关诊断
  const diagnosisMap = {
    '内科': ['高血压', '糖尿病', '胃炎', '支气管炎'],
    '外科': ['腹股沟疝', '阑尾炎', '胆囊炎', '骨折'],
    '儿科': ['上呼吸道感染', '手足口病', '过敏性鼻炎', '儿童肥胖'],
    '妇产科': ['妇科炎症', '子宫肌瘤', '多囊卵巢综合征', '产后抑郁'],
    '眼科': ['结膜炎', '白内障', '青光眼', '近视'],
    '口腔科': ['龋齿', '牙周炎', '口腔溃疡', '牙髓炎'],
    '皮肤科': ['湿疹', '痤疮', '皮炎', '带状疱疹'],
    '神经内科': ['偏头痛', '失眠症', '焦虑症', '抑郁症'],
    '心血管内科': ['心律失常', '冠心病', '心肌炎', '高血脂']
  }
  
  // 根据科室生成相关治疗方案
  const treatmentMap = {
    '内科': ['药物治疗', '生活方式干预', '中药调理', '心理疏导'],
    '外科': ['手术治疗', '物理治疗', '药物治疗', '康复训练'],
    '儿科': ['对症治疗', '抗生素治疗', '营养支持', '免疫调节'],
    '妇产科': ['药物治疗', '手术治疗', '物理治疗', '心理疏导'],
    '眼科': ['药物治疗', '激光治疗', '手术治疗', '视力训练'],
    '口腔科': ['药物治疗', '填充治疗', '拔牙治疗', '正畸治疗'],
    '皮肤科': ['外用药物', '口服药物', '激光治疗', '物理治疗'],
    '神经内科': ['药物治疗', '心理治疗', '物理治疗', '康复训练'],
    '心血管内科': ['药物治疗', '生活方式干预', '手术治疗', '康复训练']
  }
  
  // 根据科室生成相关医嘱
  const adviceMap = {
    '内科': ['规律作息', '均衡饮食', '适量运动', '定期复查'],
    '外科': ['伤口护理', '康复锻炼', '避免剧烈运动', '定期复查'],
    '儿科': ['增强免疫力', '合理饮食', '注意保暖', '定期体检'],
    '妇产科': ['个人卫生', '规律生活', '情绪调节', '定期复查'],
    '眼科': ['用眼卫生', '避免长时间用眼', '眼部保健', '定期复查'],
    '口腔科': ['口腔卫生', '正确刷牙', '少吃甜食', '定期洁牙'],
    '皮肤科': ['皮肤清洁', '避免过敏源', '保持皮肤湿润', '避免搔抓'],
    '神经内科': ['减轻压力', '规律作息', '适量运动', '避免刺激'],
    '心血管内科': ['低盐低脂饮食', '戒烟限酒', '适量运动', '定期监测血压']
  }
  
  // 获取科室名称
  const departmentName = appointmentData.departmentName || '内科'
  
  // 从对应科室的诊断、治疗方案和医嘱中随机选择
  const diagnoses = diagnosisMap[departmentName] || diagnosisMap['内科']
  const treatments = treatmentMap[departmentName] || treatmentMap['内科']
  const advices = adviceMap[departmentName] || adviceMap['内科']
  
  // 随机选择
  const diagnosisIndex = Math.floor(Math.random() * diagnoses.length)
  const treatmentIndex = Math.floor(Math.random() * treatments.length)
  const adviceIndex = Math.floor(Math.random() * advices.length)
  
  // 生成医疗记录
  generatedMedicalRecord.value = {
    id: `MR${Date.now().toString().substring(5)}`,
    patientId: appointmentData.patientId,
    doctorId: appointmentData.doctorId,
    appointmentId: appointmentData.id,
    createdAt: new Date().toISOString(),
    diagnosis: diagnoses[diagnosisIndex],
    treatment: treatments[treatmentIndex],
    advice: advices[adviceIndex],
    notes: '患者通过正常就诊流程生成的医疗记录'
  }
  
  console.log('生成模拟医疗记录:', generatedMedicalRecord.value)
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.margin-bottom {
  margin-bottom: 20px;
}

.empty-data {
  color: #909399;
  text-align: center;
  padding: 30px 0;
}

.status-alert {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.record-info {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 